<template>
    <div class="setting-page resume-page">
        <div class="setting-page-center">
            <div class="setting-page-left">
                <div class="setting-nav">
                    <div class="setting-nav-title">简历管理</div>
                    <el-menu>
                        <el-menu-item
                                :class="activeIndex === index ? 'menu-checked' : ''"
                                v-for="(item, index) in navsList"
                                @click="doNav(item,index)"
                                :key="index">
                            <span slot="title">{{item.label}}</span>
                        </el-menu-item>
                    </el-menu>
                </div>
            </div>
            <div class="setting-page-rigth">
                <job-jd v-if="activeIndex === 0" v-model="activeIndex" :params="params" @input="nextPage"
                        @spot-change="spotChange" :disabled-num="disableNum"
                        @spot-delete="spotDelete"
                ></job-jd>
                <p-a v-if="activeIndex === 1"
                     :other-req="pa.otherReq" :bonus-value="pa.bonusValue" :req-select="pa.mfSelect"
                     :must_first="pa.mfReq"
                     v-on:click-publish="doPublish"></p-a>
            </div>
        </div>
        <el-dialog
                title="提示"
                :visible.sync="showSaveQ"
                height="5%"
                width="40%">
            <div style="display:flex;justify-content:center;align-items:center;padding-top: 20px;padding-bottom:20px;">
                <span style="
                font-size:24px;
                font-weight:400;
                color:rgba(102,102,102,1);
                line-height:30px;">{{'您的职位正在编辑中，是否保存职位'+(this.jobServerId?'？':'到草稿？')}}</span>
            </div>
            <span slot="footer">
             <el-button style="
             background:rgba(247,249,252,1);
             border:1px solid rgba(230,233,240,1);
             border-radius:5px;
             font-size:24px;
             font-weight:400;
             color:rgba(153,153,153,1);"
                        @click="dialogClick('cancel')">取 消</el-button>
             <el-button style="
             border:none;
             background:rgba(240,147,56,1);
             border-radius:5px;
             font-size:24px;
             font-weight:400;
             color:white;" type="primary" @click="dialogClick('confirm')">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
  import jobJd from './jobJd'
  import PA from './PA'
  import Left from '../Left'
  import _g from '../../assets/utils/global'
  import * as qs from 'qs'
  import * as _ from 'underscore'
  import _subject from '../../assets/utils/subject'

  export default {
    name: 'index-post-job',
    beforeRouteLeave(to, from, next) {
      if (this.savedQ) {
        next()
      } else {
        this.nextPath = to.path
        next({ path: from.path, query: from.query })
        this.showSaveQ = true
      }
    },
    computed: {
      disableNum() {
        if (this.jobServerId && !this.draftQ) {
          const disabled = this.$route.query.disabled
          if (disabled) {
            return Number(disabled)
          }
        }
        return 0
      }
    },
    watch: {
      '$route': {
        immediate: true,
        handler() {
          this.initPage()
        }
      }
    },
    data() {
      return {
        lastSpots: [],
        showSaveQ: false,
        savedQ: false,
        activeIndex: 0,
        navsList: [{ label: '职位JD' }, { label: '职位PA' }],
        serverOptions: {},
        params: {
          name: null,
          number: null,
          moneyLow: null,
          moneyHigh: null,
          year: null,
          radio: '0',
          city: [],
          detail_addr: null,
          time: null,
          guarantee: null,
          describe: null,
          ask: null,
          type: [],
          spot: [],
          work_period: null,
          edu_req: null,
          validateTime: null
        },
        pa: {
          mfSelect: [[], []],
          mfReq: [{}, {}],
          otherReq: [''],
          bonusValue: []
        },
        jobServerId: null,
        subscription: null,
        nextPath: null,
        draftQ: false//是否是草稿
      }
    },
    methods: {
      initPage() {
        this.lastSpots = []
        this.showSaveQ = false
        this.savedQ = false
        this.activeIndex = 0
        this.serverOptions = {}
        this.params = {
          name: null,
          number: null,
          moneyLow: null,
          moneyHigh: null,
          year: null,
          radio: '0',
          city: [],
          detail_addr: null,
          time: null,
          guarantee: null,
          describe: null,
          ask: null,
          type: [],
          spot: [],
          work_period: null,
          edu_req: null,
          validateTime: null
        }
        this.pa = {
          mfSelect: [[], []],
          mfReq: [{}, {}],
          otherReq: [''],
          bonusValue: []
        }
        this.jobServerId = null
        this.subscription = null
        this.nextPath = null
        this.draftQ = false//是否是草稿
        let id = this.$route.query.jobServerId
        this.jobServerId = _.isUndefined(id) ? null : id
        this.loadOptions()
      },
      spotDelete(t) {
        this.params.spot = _.reject(this.params.spot, o => {
          return o === t
        })
        this.lastSpots = this.params.spot
      },
      spotChange(v) {
        if (v.length > 5) {
          _g.message('职位亮点最多选择5个', 'warning')
          this.params.spot = this.lastSpots
        } else {
          this.params.spot = v
          this.lastSpots = v
        }
      },
      getLicense(second) {
        let val = []
        _.each(this.serverOptions[13], f => {
          const fid = f.id
          _.each(f.srList, s => {
            if (s.id === second) {
              val = [fid, s.id]
            }
          })
        })
        return val
      },
      loadOptions() {
        _g.apiPost('/company/selectStaticData.do', { state: '13' })
          .then(res => {
            if (!_.isNull(res) && res.status === 0) {
              if (res && res.status === 0) {
                this.serverOptions = res.data
                //紧接着加载职位
                this.loadJob()
              }
            }
          })
      },
      dialogClick(which) {
        if (which === 'confirm') {
          let temp = [{}, {}]
          for (let c = 0; c < 2; c++) {
            for (let col of this.pa.mfSelect[c]) {
              if (col === '执业类型') {
                temp[c][col] = this.pa.mfReq[c][col][1]
              } else {
                temp[c][col] = this.pa.mfReq[c][col]
              }
            }
          }
          this.saveDraft(temp, this.pa.otherReq[0], this.pa.bonusValue)
        } else {
          this.savedQ = true
          if (this.nextPath) {
            if (this.$route.query.hasOwnProperty('which')) {
              this.$router.push({ path: this.nextPath, query: { which: this.$route.query.which } })
            } else {
              this.$router.push({ path: this.nextPath })
            }
          }
          this.showSaveQ = false
        }
      },
      doNav(item, index) {
        this.activeIndex = index
      },
      validateParams: function() {
        for (let col in this.params) {
          if (_.isNull(this.params[col])) {
            _g.message('请填写完必填参数', 'warning')
            return false
          } else {
            if (_.isArray(this.params[col]) && this.params[col].length === 0) {
              _g.message('请填写完必填参数', 'waring')
              return false
            }
          }
        }
        if (this.params.moneyLow < 10) {
          _g.message('最低年薪不能小于10', 'waring')
          return false
        }
        if (this.params.moneyLow > this.params.moneyHigh) {
          _g.message('最低年薪不能大于最高年薪', 'waring')
          return false
        }
        if (this.params.moneyHigh - this.params.moneyLow > 5) {
          _g.message('最低年薪和最高年薪的差距不能超过5', 'waring')
          return false
        }
        if (this.params.validateTime > 90 || this.params.validateTime < 1) {
          _g.message('职位有效期在1~90之间', 'waring')
          return false
        }
        return true
      },
      nextPage: function() {
        const validQ = this.validateParams()
        this.activeIndex = validQ ? 1 : 0
      },
      skipNull: function(o) {
        return JSON.stringify(qs.parse(qs.stringify(o, { skipNulls: true })))
      },
      saveDraft(req, other, bonus) {
        if (!this.draftQ) {
          //不是草稿，需要检查参数
          if (!this.validateParams()) {
            return
          }
        }
        const params = {
          jobId: this.jobServerId,
          companyId: null,
          name: this.params.name,
          recruitingNumbers: this.params.number,
          salaryPerMonthLow: this.params.moneyLow,
          salaryPerMonthHigh: this.params.moneyHigh,
          salaryCount: this.params.year,
          tax: this.params.radio,
          jobSpot: this.params.spot.join(','),
          jobDesc: this.params.describe,
          jobReq: this.params.ask,
          province: this.params.city[0],
          city: this.params.city[1],
          address: this.params.detail_addr,
          interFeedbackTimeId: this.params.time,
          guaranteedPeriodId: this.params.guarantee,
          licenseTypeId: this.params.type[1],
          workTime: this.params.work_period,
          eduReq: this.params.edu_req,
          ageReq: null,
          validity: this.params.validateTime,
          validityTime: null,
          bonus: null,
          rdtime: null,
          talentNecessaryReq: this.skipNull(req[0]),
          talentPriorityReq: this.skipNull(req[1]),
          talentOtherReq: other,
          welfareSalary: bonus[0],
          welfareSociety: bonus[1],
          welfareVacation: bonus[2],
          welfareTransport: bonus[3],
          releases: null,
          checkState: null,
          jobState: this.draftQ ? 3 : null,
          workTimePa: null,
          ageReqPa: null,
          sexReqPa: null,
          licenseTypeIdPa: null,
          eduReqPa: null,
          schoolReqPa: null,
          stabilityPa: null,
          releasesTime: null,
          releasesUser: null,
          checkUser: null,
          checkTime: null,
          jobStateTime: null,
          jobStateUser: null,
          probationPeriod: null,
          recommendNums: null,
          onlineResumeNums: null,
          onlResRecommendNums: null,
          workTimeStr: null,
          eduReqStr: null,
          interFeedbackTimeIdStr: null,
          guaranteedPeriodIdStr: null,
          licenseTypeIdStr: null
        }
        if (_.isNull(this.jobServerId)) {
          _g.apiPost('/company/insertJob.do', params)
            .then(res => {
              if (!_.isNull(res) && res.status === 0) {
                _g.message('您的职位信息已保存到草稿', 'success')
                this.savedQ = true
                this.$router.push('/job')
              }
            })
        } else {
          //为异步，所以先要保存起来
          const query = this.$route.query
          _g.apiPost('/company/updateJob.do', params)
            .then(res => {
              if (!_.isNull(res) && res.status === 0) {
                if (this.draftQ) {
                  _g.message('您的草稿信息已更新', 'success')
                } else {
                  if (query.hasOwnProperty('which') && (query.which === '1' || query.which === '2')) {
                    _g.message('发布成功', 'success')
                  } else {
                    _g.message('您的职位信息已提交，平台正在审核中，如有疑问请联系专属顾问', 'success')
                  }
                }
                this.savedQ = true
                if (this.nextPath) {
                  if (query.hasOwnProperty('which')) {
                    this.$router.push({ path: this.nextPath, query: { which: query.which } })
                  } else {
                    this.$router.push({ path: this.nextPath })
                  }
                }
                this.showSaveQ = false
              }
            })
        }
      },
      doPublish(req, other, bonus) {
        const validQ = this.validateParams()
        if (!validQ) return
        const params = {
          jobId: this.jobServerId,
          companyId: null,
          name: this.params.name,
          recruitingNumbers: this.params.number,
          salaryPerMonthLow: this.params.moneyLow,
          salaryPerMonthHigh: this.params.moneyHigh,
          salaryCount: this.params.year,
          tax: this.params.radio,
          jobSpot: this.params.spot.join(','),
          jobDesc: this.params.describe,
          jobReq: this.params.ask,
          province: this.params.city[0],
          city: this.params.city[1],
          address: this.params.detail_addr,
          interFeedbackTimeId: this.params.time,
          guaranteedPeriodId: this.params.guarantee,
          licenseTypeId: this.params.type[1],
          workTime: this.params.work_period,
          eduReq: this.params.edu_req,
          ageReq: null,
          validity: this.params.validateTime,
          validityTime: null,
          bonus: null,
          rdtime: null,
          talentNecessaryReq: this.skipNull(req[0]),
          talentPriorityReq: this.skipNull(req[1]),
          talentOtherReq: other,
          welfareSalary: bonus[0],
          welfareSociety: bonus[1],
          welfareVacation: bonus[2],
          welfareTransport: bonus[3],
          releases: null,
          checkState: null,
          jobState: 0,//无论草稿还是啥，都应该是0
          workTimePa: null,
          ageReqPa: null,
          sexReqPa: null,
          licenseTypeIdPa: null,
          eduReqPa: null,
          schoolReqPa: null,
          stabilityPa: null,
          releasesTime: null,
          releasesUser: null,
          checkUser: null,
          checkTime: null,
          jobStateTime: null,
          jobStateUser: null,
          probationPeriod: null,
          recommendNums: null,
          onlineResumeNums: null,
          onlResRecommendNums: null,
          workTimeStr: null,
          eduReqStr: null,
          interFeedbackTimeIdStr: null,
          guaranteedPeriodIdStr: null,
          licenseTypeIdStr: null
        }
        if (_.isNull(this.jobServerId)) {
          _g.apiPost('/company/insertJob.do', params)
            .then(res => {
              if (!_.isNull(res) && res.status === 0) {
                _g.message('您的职位信息已提交，平台正在审核中，如有疑问请联系专属顾问', 'success')
                this.savedQ = true
                this.$router.push('/job')
              }
            })
        } else {
          _g.apiPost('/company/updateJob.do', params)
            .then(res => {
              if (res && res.status === 0) {
                if (this.draftQ) {
                  _g.message('您的草稿已提交，平台正在审核中，如有疑问请联系专属顾问', 'success')
                } else {
                  if (this.$route.query.hasOwnProperty('which') && (this.$route.query.which === '1' || this.$route.query.which === '2')) {
                    _g.message('发布成功', 'success')
                  } else {
                    _g.message('您的职位信息已提交，平台正在审核中，如有疑问请联系专属顾问', 'success')
                  }
                }
                this.savedQ = true
                if (this.$route.query.hasOwnProperty('which')) {
                  this.$router.push({ path: '/job', query: { which: this.$route.query.which } })
                } else {
                  this.$router.push({ path: '/job' })
                }
              }
            })
        }
      },
      loadJob: function() {
        if (!_.isNull(this.jobServerId)) {
          _g.apiPost('/company/selectJobInfo.do', { jobId: this.jobServerId })
            .then(res => {
              if (res && res.status === 0) {
                //查询执业类型
                const job = res.data
                this.params.name = job.name
                this.params.number = job.recruitingNumbers
                this.params.moneyLow = job.salaryPerMonthLow
                this.params.moneyHigh = job.salaryPerMonthHigh
                this.params.year = job.salaryCount
                this.params.city.splice(0, this.params.length, job.province, job.city)
                this.params.detail_addr = job.address
                this.params.time = job.interFeedbackTimeId
                this.params.guarantee = job.guaranteedPeriodId
                this.params.describe = job.jobDesc
                this.params.ask = job.jobReq
                this.params.type = this.getLicense(job.licenseTypeId)
                this.params.spot = job.jobSpot ? job.jobSpot.split(',') : []
                this.params.work_period = job.workTime
                this.params.edu_req = job.eduReq
                this.params.validateTime = job.validity
                this.draftQ = job.jobState === 3
                if (!_.isNull(job.talentNecessaryReq)) {
                  const m = JSON.parse(job.talentNecessaryReq)
                  if (!_.isNull(m)) {
                    this.pa.mfSelect[0] = []
                    _.each(_.keys(m), o => {
                      this.pa.mfSelect[0].push(o)
                      if (o === '执业类型') {
                        this.pa.mfReq[0][o] = this.getLicense(Number(m[o]))
                      } else {
                        this.pa.mfReq[0][o] = Number(m[o])
                      }
                    })
                  }
                }
                if (!_.isNull(job.talentPriorityReq)) {
                  const f = JSON.parse(job.talentPriorityReq)
                  if (!_.isNull(f)) {
                    this.pa.mfSelect[1] = []
                    _.each(_.keys(f), o => {
                      this.pa.mfSelect[1].push(o)
                      if (o === '执业类型') {
                        this.pa.mfReq[1][o] = this.getLicense(Number(f[o]))
                      } else {
                        this.pa.mfReq[1][o] = Number(f[o])
                      }
                    })
                  }
                }
                this.pa.otherReq[0] = job.talentOtherReq
                this.pa.bonusValue.splice(0, this.pa.bonusValue.length, job.welfareSalary, job.welfareSociety, job.welfareVacation, job.welfareTransport)
              }
            })
        } else {
          this.draftQ = true
        }
      }
    },
    components: {
      Left: Left,
      jobJd,
      PA: PA
    },
    created() {
      this.initPage()
    }
  }
</script>

<style lang="scss" scoped>

</style>
